 /**
* @Description: 菜单权限模板
* @author  tangbin
* @date 2023/3/9
*/

<template>
  <div class="app-container">
    <div class="page-search-wrap" id="searchForm">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px" @submit.native.prevent v-show="showSearch">
        
        <el-form-item label="所属租户级别" prop="level">
          <el-select
            size="small"
            v-model="queryParams.level"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_tenant_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="模板名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入模板名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="com-tabel" id="comTabel">
      <div class="bg-line"></div>
      <div class="m-t-search clearfix">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:template:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <!-- <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['agent:template:edit']"
            >修改</el-button> -->
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['system:template:del']"
            >删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['agent:template:export']"
            >导出</el-button>
          </el-col> -->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </div>
    </div>

    <div class="page-table">
      <el-table 
        v-loading="loading" 
        :data="templateList" 
        @selection-change="handleSelectionChange"
        ref="filterTable"
        :style="{height: height + 'px', minHeight: 200 + 'px'}"
        :height="height"
        >
        <el-table-column type="selection" width="60" align="center" />
        <el-table-column label="所属租户级别" align="center" prop="level" :formatter="levelFormat" />
        <el-table-column label="模板名称" align="center" prop="name" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column fixed="right" label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:template:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:template:del']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>


    <!-- 添加或修改权限模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入模板名称" size="small" maxlength="50" />
        </el-form-item>

        <el-form-item label="所属租户级别" prop="level">
          <el-select
            size="small"
            v-model="form.level"
            placeholder="请选择"
            clearable
            style="width: 100%"
            :disabled="disabledLevel"
          >
            <el-option
              v-for="dict in levels"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              :disabled="dict.disabled"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="菜单权限" prop="menus">
          <!-- <el-input v-model="form.menus" v-show="true"></el-input> -->
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="暂无数据"
            :props="defaultProps"
            @check="treeCheck"
          ></el-tree>
        </el-form-item>

        <!-- <el-form-item label="菜单权限" class="menuThority">
          <el-tree
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item> -->
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" rows="5" maxlength="500" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled='disabled'>确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    
  </div>
</template>

<script>
import { treeselect } from '@/api/system/menu.js'
import {listTemplate, templateDetail, addTemplate, updateTemplate, deleteTemplate} from "@/api/system/permission"

export default {
  name: "permission",
  dicts: ['sys_tenant_level'],
  data() {
    return {
      height: 200,
      disabled:false,

      // 显示搜索条件
      showSearch: true,

      levels: [],

      disabledLevel: true,

      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      templateName:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 权限模板表格数据
      templateList: [],

      // tenantLevels:[], // 租户级别

      // 所有菜单列表
      menuOptions: [],

      menuExpand: false, // 是否展开折叠
      menuNodeAll: false, // 是否全选

      defaultProps: {
        children: "children",
        label: "label"
      },

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        level: undefined
      },
      // 表单参数
      form: {
        menus: undefined, // 菜单是否有选中的项
        menuIds: [],
        menuCheckStrictly: true, // 是否父子联动
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        level: [
          { required: true, message: "所属租户层级不能为空", trigger: "blur" }
        ],
        menus: [
        { required: true, message: "请选择菜单权限", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    // this.menumTreeSelect();
  },
  activated() {
    this.tableHeight();
  },
  updated() {
    // 解决表格设置固定高度导致列设置fixed后重新进来会错行问题
    this.tableHeight();
    this.$nextTick(() => {
      this.$refs.filterTable.doLayout();
    });
  },
  methods: {

    tableHeight() {
      this.$nextTick(() => {
        let height = document.body.clientHeight - 90 - 40;
        // 查询表单高度
        let s_height = document.getElementById('searchForm').clientHeight;
        // 按钮容器高度
        let btns_height = document.getElementById('comTabel').clientHeight;
        // 计算表格的高度
        this.height = height - s_height - btns_height - (this.total > 0 ? 60 : 0);
      });
    },

    /** 查询权限模板列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.data.records;
        this.total = parseInt(response.data.total);
        this.loading = false;
      });
    },

    /**
     * 所属租户级别
     * @param {*} row 
     * @param {*} column 
     */
     levelFormat(row, column) {
      let show = '';
      this.dict.type.sys_tenant_level.some((item) => {
        // console.log('item=', item.value);
        // console.log('level=', row.level);
        if (row.level == item.value) {
          show = item.label;
          return true;
        }
      });
      return show;
    },

    /**
     * 树权限（展开/折叠）
     * @param {*} value 
     * @param {*} type 
     */
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    
    /**
     * 树权限（全选/全不选）
     * @param {*} value 
     * @param {*} type 
     */
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
      }
    },
    
    /**
     * 树权限（父子联动）
     * @param {*} value 
     * @param {*} type 
     */
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true: false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true: false;
      }
    },

    /**
     * 初始化租户级别
     */
    //  setupTenantLevels() {
    //   // console.log('eeeeeeee=', this.dict.type.sys_tenant_level);
    //   this.tenantLevels = [];
    //   const list = this.dict.type.sys_tenant_level;
    //   list.forEach((item) => {
    //     // console.log('item=', item);
    //     this.tenantLevels.push(item);
    //     // if (item.value !== '0') {
    //     //   this.tenantLevels.push(item);
    //     // }
    //   });
    // },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        menus: undefined,
        menuCheckStrictly: true,
        id: undefined,
        name: undefined,
        level: undefined,
        menuIds: [],
        remark: undefined
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      // console.log(this.queryParams)
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      // console.log(this.ids)

      this.templateName = selection.map(item => item.name);
      this.single = (selection.length != 1);
      this.multiple = !selection.length;
    },

    setupLevels() {
      // console.log('dict.type.sys_tenant_level=', this.dict.type.sys_tenant_level);
      this.levels = [];
      this.dict.type.sys_tenant_level.forEach((item) => {
        if (item.value !== '0') {
          item = {...item, disabled:false};
          // disabled
        } else {
          item = {...item, disabled:true};
        }
        this.levels.push(item);
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.disabledLevel = false;
      this.setupLevels();
      this.open = true;
      this.title = "添加权限模板";
      this.getMenuTreeselects().then(data => {
        console.log('data=', data);
        this.menuOptions = data;
        this.$refs.menu.setCheckedKeys([]);
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log('row=', row);
      this.reset();
      this.setupLevels();
      this.disabledLevel = false;
      if (row.level == 0) {
        this.disabledLevel = true;
      }
      const tempId = row.id || this.ids
      const params = {templateId:tempId};
      templateDetail(params).then(tempData => {
        this.form = tempData.data;
        this.form.level = this.form.level + '';
        this.form = {
          ...this.form,
          menuCheckStrictly: true,
          menus: (tempData.data.menuIds.length > 0 ?'有了': undefined)
        };
        this.open = true;
        this.title = "修改权限模板";
        this.getMenuTreeselects().then(data => {
          this.menuOptions = data;
          tempData.data.menuIds.forEach((v) => {
                this.$nextTick(()=>{
                    this.$refs.menu.setChecked(v, true ,false);
                })
            })
        });
      });

    },
    

    /** 查询菜单树结构 */
    getMenuTreeselects() {

      return treeselect().then(res => {
        return res.data;
      });

      // return listAllMenus(tempId).then(respData => {
      //   return respData;
      // });
    },

    /**
     * 点击tree
     * @param {*} item 
     * @param {*} de 
     */
    treeCheck(item, data) {
      // console.log('item=', item);
      // console.log('de=', data.checkedNodes);
      if (data.checkedNodes.length > 0) {
        // console.log('才有了');
        this.form.menus = '有了';
      } else {
        this.form.menus = undefined;
      }
    },

    /** 提交按钮 */
    submitForm: function() {
      this.disabled = true;
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 目前被选中的菜单节点
          let checkedKeys = this.$refs.menu.getCheckedKeys();
          // 半选中的菜单节点
          let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
          let menuIds =[...checkedKeys, ...halfCheckedKeys]
          if(menuIds.length === 0){
            this.$modal.msgError('菜单权限不能为空')
            this.disabled=false
            return
          }
          // let count = 0
          // menuIds.indexOf('2321') > -1 && count++
          // menuIds.indexOf('2322') > -1 && count++
          // if (count === 0) {
          //   this.$modal.msgWarning('首页、首页-老板与首页-员工必须选择一个');
          //   this.disabled = false;
          //   return
          // }

          let params = {
            menuIds: menuIds,
            name: this.form.name,
            level: this.form.level,
            remark: this.form.remark,
          }

          if (this.form.id != undefined) {
            // console.log('修改');
            params.id = this.form.id
            updateTemplate(params).then(respData => {
              if (respData) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.disabled = false;
                this.getList();
              }
            }).catch(err => {
              this.disabled = false;
            });
          } else {
            // console.log('添加');
            addTemplate(params).then(respData => {
              if (respData) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.disabled = false;
                this.getList();
              }
            }).catch(err => {
              this.disabled = false;
            });
          }
          // setTimeout(()=>{
          //   this.disabled = false;
          // },2000)
        }else{
          this.disabled = false;
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row? [row.id] : this.ids;
      this.$modal.confirm('是否确认删除权限模板名称为"' + (row?.name||this.templateName) + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return deleteTemplate({templateIds:ids});
        }).then((dta) => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(function() {});
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = {
        name: this.queryParams.name,
        level: this.queryParams.level
      };


      this.$modal.confirm('是否确认导出所有权限模板数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.downloadFile('/system/tenant/template/export', queryParams, `template_${Date.now()}.xls`);
      })
    }
  }
};
</script>
<style lang="less">
 .menuThority{
   position: relative;
 }
 .menuThority:after{
   position: absolute;
   content: '*';
   color:#ff4949;
   left:0;
   font-size:14px;
   top:10px;
   font-weight: bold;
 }
</style>
